package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Description TODO
 * @Date 2024/3/29 14:56
 * @Author ShaoJie Cen
 */
@Configuration
public class RedisConfig {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    // 创建RedisTemplate Bean
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();

        // 设置Key的序列化方式
        template.setKeySerializer(new StringRedisSerializer());

        // 设置Value的序列化方式，这里以Object为例，可以替换成自己所需的序列化器
        template.setValueSerializer(new GenericToStringSerializer<>(Object.class));

        // 对于Hash类型的Key和Value的序列化同样可以进行自定义
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericToStringSerializer<>(Object.class));

        // 设置连接工厂
        template.setConnectionFactory(redisConnectionFactory);

        return template;
    }


}
